package com.base.cn.platform.os.service.favorites;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.dao.course.favorites.CourseFavoritesDao;
import com.base.cn.platform.os.entity.course.cou.CourseProfile;
import com.base.cn.platform.os.entity.course.favorites.CourseFavorites;
import com.base.cn.platform.os.service.course.cou.CourseProfileBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 课程收藏Biz
 *
 * @author s.li
 * @date 2018/10/24
 */
@Service
public class CourseFavoritesBiz extends BaseBiz<CourseFavorites, CourseFavoritesDao> {

    @Autowired
    private CourseProfileBiz courseProfileBiz;

    /**
     * 保存用户收藏课程
     * @param userId 用户ID
     * @param courseId 课程ID
     */
    public Map<String,Object> saveCourseFavorites(BigDecimal userId,BigDecimal courseId){
        Map<String,Object> result = new HashMap<>();
        CourseFavorites courseFavorites = this.findOne(" userId="+userId +" and courseId="+courseId,null);
        CourseProfile courseProfile = courseProfileBiz.findById(courseId);
        if(ObjectUtils.isEmpty(courseFavorites)){//未收藏过，添加收藏
            courseFavorites = new CourseFavorites();
            courseFavorites.setUserId(userId);
            courseFavorites.setCourseId(courseId);
            this.save(courseFavorites);
            courseProfile.setFavoritesCount(courseProfile.getFavoritesCount().intValue() + 1);
            result.put("status","add");
        }else{//已收藏过，删除收藏
            this.deleteWhereSql(" userId="+userId +" and courseId = "+courseId);
            courseProfile.setFavoritesCount(courseProfile.getFavoritesCount().intValue() - 1);
            result.put("status","cancel");
        }
        courseProfileBiz.updateById(courseProfile,null);
        result.put("courseProfile",courseProfile);
        return result;
    }

    /**
     * 获取用户的单个课程收藏记录
     * @param userId 用户ID
     * @param courseId 课程ID
     * @return CourseFavorites
     */
    public CourseFavorites findUserCourseFavorites(BigDecimal userId,BigDecimal courseId){
        return this.findOne(" userId= "+userId+" and courseId = "+courseId,null);
    }
}
